package pos.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import pos.domain.*;

public class JDBCBarrioDAO implements IBarrioDAO {

	Connection conn = ConnectionManager.getInstance().getConn();

	@Override
	public Barrio selectById(int idBarrio) {
		PreparedStatement stmt = null;
		ResultSet result = null;
		Barrio b = null;
		String sql = "SELECT * FROM barrio WHERE (idBarrio = ?) ";

		try {
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, idBarrio);
			result = stmt.executeQuery();

			if (result.next()) {
				b = new Barrio();
				b.setIdBarrio(result.getInt("idBarrio"));
				b.setNombre(result.getString("nombre"));
				b.setColindantes(getColindantes(b));
			}

		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (result != null) {
					result.close();
				}
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException e) {
			}
		}
		return b;
	}

	private List<Integer> getColindantes(Barrio barrio) {
		PreparedStatement stmt = null;
		ResultSet result = null;
		String sql = "SELECT * FROM barriocolindante WHERE idBarrio = ?";
		List<Integer> lista = new ArrayList<Integer>();

		try {
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, barrio.getIdBarrio());
			result = stmt.executeQuery();

			while (result.next()) {

				lista.add(result.getInt("idBarrioColindante"));
			}

		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (result != null) {
					result.close();
				}
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException e) {
			}
		}
		return lista;
	}

	@Override
	public Barrio selectByNombre(String nombre) {
		PreparedStatement stmt = null;
		ResultSet result = null;
		Barrio b = null;
		// String nombreBarrio ="%"+nombre+"%";
		String sql = "SELECT * FROM barrio WHERE (nombre like ?) ";

		try {
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, nombre);
			result = stmt.executeQuery();

			if (result.next()) {
				b = new Barrio();
				b.setIdBarrio(result.getInt("idBarrio"));
				b.setNombre(result.getString("nombre"));
				b.setColindantes(getColindantes(b));
			}

		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (result != null) {
					result.close();
				}
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException e) {
			}
		}
		return b;
	}

}
